package cn.dida.controller;

import cn.dida.exception.BizzException;
import cn.dida.model.Company;
import cn.dida.model.Department;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.UserSession;
import cn.dida.service.CompanyService;
import cn.dida.service.DepartmentService;
import cn.dida.weixin.qyh.QyhApiClient;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 部门管理
 * @author weiwei
 *
 */
@Controller
public class DepartmentController extends BaseController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private CompanyService companyService;

    /**
     * 部门列表
     * @param request
     * @param keyword 查询条件
     * @param page 分页游标
     * @return ModelAndView 部门列表页面
     * @throws Exception
     */
    @GetMapping("/department")
    public ModelAndView department(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        //获取部门列表
        List<Department> departmentList = departmentService.getAllDepartment(userSession.getCompanyId());

        //从企业号导入顶级部门
        if (CollectionUtils.isEmpty(departmentList)) {
            Company company = companyService.getCompany(userSession.getCompanyId());
            JSONObject preference = JSONObject.parseObject(company.getPreference());
            String corpid = preference.getString("weixin_qyh_corpid");
            String corpsecret = preference.getString("weixin_qyh_corpsecret");
            QyhApiClient qyhApiClient = new QyhApiClient(corpid, corpsecret);

            JSONObject re = qyhApiClient.getDepartmentList(1);
            if (re.getInteger("errcode") == 0) {
                JSONArray departmentArray = re.getJSONArray("department");

                for (int i = 0; i < departmentArray.size(); i++) {
                    JSONObject depObj = departmentArray.getJSONObject(i);
                    if (depObj.getInteger("id") == 1) {
                        Department department = new Department();
                        department.setId(depObj.getInteger("id"));
                        department.setCompanyId(company.getId());
                        department.setName(depObj.getString("name"));
                        departmentService.insertDepartmentWithoutSync(department);
                        departmentList = departmentService.getAllDepartment(userSession.getCompanyId());
                        break;
                    }
                }
            }
        }

        //组织成树结构
        List<Department> departmentTree = makeDepartmentTree(departmentList);
        model.put("departmentList", departmentTree);
        return new ModelAndView("department_list").addAllObjects(model);
    }

    /**
     * 部门列表树
     * @param request
     * @param type
     * @return HttpResponseBodyWrapper 包装部门列表树数据
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/department/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object upload(HttpServletRequest request, Integer type) throws Exception {
        UserSession userSession = getUserSession(request);
        //获取部门列表
        List<Department> departmentList = departmentService.getAllDepartment(userSession.getCompanyId());
        List<Department> departmentTree = makeDepartmentTree(departmentList);
        return new HttpResponseBodyWrapper(departmentTree);
    }

    /**
     * 新增部门
     * @param request
     * @param department 部门实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/department")
    public HttpResponseBodyWrapper postDepartment(HttpServletRequest request, @RequestBody Department department) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        department.setName(StringUtils.trimToNull(department.getName()));
        department.setCompanyId(userSession.getCompanyId());

        if (department.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入品牌名称");
        }
        if (department.getParentId() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择父部门");
        }

        Boolean result = departmentService.insertDepartment(department);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 更新部门
     * @param request
     * @param department 部门实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
     * @throws Exception
     */
    @ResponseBody
    @PutMapping("/department/{id}")
    public HttpResponseBodyWrapper putDepartment(HttpServletRequest request, @RequestBody Department department) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        department.setName(StringUtils.trimToNull(department.getName()));
        department.setCompanyId(userSession.getCompanyId());
        if (department.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入品牌名称");
        }
        if (department.getParentId() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请选择父部门");
        }

        Boolean result = departmentService.updateDepartment(department);
        return new HttpResponseBodyWrapper(result);
    }
    
    /**
     * 删除部门
     * @param request
     * @param id 部门id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     * @throws Exception
     */
    @ResponseBody
    @DeleteMapping("/department/{id}")
    public HttpResponseBodyWrapper deleteDepartment(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Boolean result = departmentService.deleteDepartment(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 组织成树结构
     * @param departmentList 部门列表数据
     * @return List<Department> 树形部门列表
     */
    private List<Department> makeDepartmentTree(List<Department> departmentList) {
        List<Department> departmentTree = new ArrayList<>();
        for (Department department1 : departmentList) {
            if (department1.getParentId() == null) {
                departmentTree.add(department1);
            } else {
                for (Department department2 : departmentList) {
                    if (department1.getParentId().intValue() == department2.getId().intValue()) {
                        department1.setParent(department2);
                        department2.getChildren().add(department1);
                    }
                }
            }
        }
        return departmentTree;
    }


}
